﻿using ComLib.ComType;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using IDCardReader;
using System.IO.Ports;
using LogLib;
using Newtonsoft.Json;
using DeviceCommon;

namespace SDTReaderDemo
{
    public partial class Form1 : Form
    {
        private SDTReader _reader = null;

        private IDCardAll _cardInfo = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void OnReadSuccess(string outParams)
        {
            string msg = $"读取结果: \n{outParams}";
            Log.WriteAsync(msg);
            try
            {
                // 在这里处理身份证信息解析结果
                _cardInfo = JsonConvert.DeserializeObject<IDCardAll>(outParams);
                ShowCardInfo();
            }
            catch (Exception ex)
            {
                Log.WriteExceptionAsync(ex.ToString());
                MessageBox.Show($"解析读取身份证信息结果发生了异常:\n{ex.Message}");
            }
        }

        private void ShowCardInfo()
        {
            if (this.InvokeRequired)
            {
                Action handler = new Action(ShowCardInfo);
                this.Invoke(handler);
                return;
            }
            textBoxAdress.Text = _cardInfo.address;
            textBoxBirthDay.Text = _cardInfo.birthday;
            textBoxIdNo.Text = _cardInfo.number;
            textBoxIssueBy.Text = _cardInfo.signdate;
            textBoxName.Text = _cardInfo.name;
            textBoxNation.Text = _cardInfo.people;
            textBoxSex.Text = _cardInfo.sex;
            textBoxValidUntil.Text = $"{_cardInfo.validtermOfStart}-{_cardInfo.validtermOfEnd}";
            if (pictureBoxHead.Image != null)
            {
                pictureBoxHead.Image.Dispose();
                pictureBoxHead.Image = null;
            }
            //pictureBoxHead.Image = new Bitmap(_cardInfo.HeadImage);
            labelStatus.Text = $"{LogConfig.Now().ToString("yyyy-MM-dd HH:mm:ss.fffff")}: 身份信息读取成功!";
        }

        private void InitComboBoxCom()
        {
            string[] ports = SerialPort.GetPortNames();
            comboBoxCom.Items.Clear();
            comboBoxCom.Items.AddRange(ports);
            string comNo = $"COM{_reader.Option.SerialPortNum}";
            for (int i = 0; i < ports.Length; i++)
            {
                if (comNo.Equals(ports[i]))
                {
                    comboBoxCom.SelectedIndex = i;
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _reader = new SDTReader();
            _reader.WorkingCompleted += OnReadSuccess;
            _reader.DoFailed += OnReadFailed;
            _reader.DoTimeout += OnReadTimeout;
            InitComboBoxCom();
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            if (_reader.Inited)
            {
                return;
            }
            if (comboBoxCom.SelectedIndex == -1)
            {
                MessageBox.Show("未选择指定连接的Com口.");
                return;
            }
            int port = 1;
            string comNo = comboBoxCom.SelectedItem.ToString();
            comNo = comNo.ToUpper();
            if (comNo.Contains("COM"))
            {
                int start = comNo.IndexOf("COM");
                start += 3;
                string portStr = comNo.Substring(start);
                port = int.Parse(portStr);
            }
            else
            {
                labelStatus.Text = "未找到符合条件的串口.";
                return;
            }
            if (_reader.OpenPort(port))
            {
                labelStatus.Text = "阅读器初始化成功!";
            }
            else
            {
                labelStatus.Text = $"阅读器初始化失败: {_reader.ErrorMessage}.";
            }
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            if (!_reader.Inited)
            {
                return;
            }
            if (_reader.Exited)
            {
                return;
            }
            if (_reader.Close())
            {
                labelStatus.Text = $"阅读器卸载成功!";
            }
            else
            {
                labelStatus.Text = $"阅读器卸载失败: {_reader.ErrorMessage}";
            }
        }

        private void buttonTest_Click(object sender, EventArgs e)
        {

        }

        private void buttonSettings_Click(object sender, EventArgs e)
        {
            FormSetting form = new FormSetting();
            form.ShowDialog();
        }

        private void buttonStartRead_Click(object sender, EventArgs e)
        {

        }

        private void buttonStopRead_Click(object sender, EventArgs e)
        {

        }

        private void buttonReadOnce_Click(object sender, EventArgs e)
        {            
            if (_reader.ReadCard(out _cardInfo))
            {
                ShowCardInfo();
            }
            else
            {
                labelStatus.Text = $"{LogConfig.Now().ToString("yyyy-MM-dd HH:mm:ss")}: {_reader.ErrorMessage}";
            }
        }

        protected void OnReadTimeout(string message)
        {
            if (this.InvokeRequired)
            {
                DoTimeoutHandler handler = new DoTimeoutHandler(OnReadTimeout);
                this.BeginInvoke(handler, new object[] { message });
                return;
            }
            labelStatus.Text = $"{LogConfig.Now().ToString("yyyy-MM-dd HH:mm:ss")}: {message}";
        }

        protected void OnReadFailed(string error)
        {
            if (this.InvokeRequired)
            {
                DoFailedHandler handler = new DoFailedHandler(OnReadFailed);
                this.BeginInvoke(handler, new object[] { error });
                return;
            }
            labelStatus.Text = $"{LogConfig.Now().ToString("yyyy-MM-dd HH:mm:ss")}读取失败: {error}";
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(_reader.Inited && !_reader.Exited)
            {
                _reader.Close();
            }
        }
    }
}
